package com.lagou.module4_6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author wsl
 * @date 2021/8/1 18:12
 * @project_name javase
 */
public class Server {//服务端

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s = null;
        BufferedReader br = null;
        PrintStream ps = null;

        try {
            //1.创建ServerSocket类型的对象并提供端口号
            ss = new ServerSocket(8888);

            //2.等待客户端的连接请求，调用accept方法
            System.out.println("等待客户端的连接请求...");
            s = ss.accept();
            System.out.println("客户端"+s.getInetAddress()+"连接成功!");

            //3.使用输入输出流进行通信
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());

            while (true) {
                String str = br.readLine();
                InetAddress inetAddress = s.getInetAddress();
                System.out.println("客户端" + inetAddress + "发来的字符串内容是：" + str);
                //当客户端发来的内容为“end”时，则聊天结束。
                if ("end".equalsIgnoreCase(str)) {
                    System.out.println("客户端" + inetAddress + "已下线！");
                    break;
                }
                //实现服务器向客户端用户发送字符串内容"I receive!"
                ps.println("I receive!");
                System.out.println("服务器发送数据成功！");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭Socket并释放相关的资源
            if (null != ps){
                ps.close();
            }
            if (null != br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
